﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace ETWebApi2.ETWeiXin
{
    public class WeiXinSendMessage
    {
        string m_processID = "WeiXinProcessID"; //"WeiXinCorpKey" "WeiXinCorpID" 程序Debug组的应用ID
        string m_token = ""; //令牌   
        public WeiXinSendMessage(HttpApplicationState app)
        {
            m_processID = GetAK(m_processID);

            if (app["weixin_token"] != null)
                m_token = app["weixin_token"].ToString();
            else
            {
                m_token = "";
                app.Add("weixin_token", m_token);
            }
        }
        public WeiXinSendMessage()
        {
        }


        public void SaveToken(HttpApplicationState app)
        {
            if (m_token.Length > 3)
            {
                if (app["weixin_token"] != null)
                    app["weixin_token"] = m_token;
                else
                    app.Add("weixin_token", m_token);
            }
        }

        //用于主动向用户发送消息
        public int Send(string who, string text)
        {
            string[] ls = new string[8];

            ls[0] = "touser";
            ls[1] = who;
            ls[2] = "msgtype";
            ls[3] = "text";
            ls[4] = "agentid";
            ls[5] = m_processID;
            ls[6] = "text";
            ls[7] = ToJson("content", text);

            string rtn = ToJson(ls);

            return SafeSendTxt(rtn);
        } 

        //合成一个只包含一对{}，一对名/值的Json数据
        private string ToJson(string name, string val)
        {
            return "{" + string.Format("\"{0}\": \"{1}\"", name, val) + "}";
        }

        //合成一个只包含一对{}的Json数据
        private string ToJson(string[] text)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("{");

            for (int i = 0; i < text.Length; i += 2)
            {
                if (text[i + 1].Length > 0 && text[i + 1][0] == '{')
                    sb.AppendFormat("\"{0}\": {1},", text[i], text[i + 1]);
                else
                    sb.AppendFormat("\"{0}\": \"{1}\",", text[i], text[i + 1]);
            }

            sb[sb.Length - 1] = '}';

            return sb.ToString();
        }


        private bool CheckNumber(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^[0-9]+$");
                System.Text.RegularExpressions.Match ma = reg.Match(str);
                return ma.Success;
            }
            else { return false; }
        }

        /// <summary>
        ///  发送Json文本,返回0表示成功,返回-1表示内部错误 其他返回WEIXIN返回码
        /// </summary>
        /// <param name="txt">Json文本</param>
        private int SendTxt(string txt)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(txt);

            string url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + m_token;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;

            Stream newStream = webRequest.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();

            //发送请求
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            //得到返回结果
            StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string rtn = php.ReadToEnd();

            string error = "\"errcode\":";

            int index = rtn.IndexOf(error);
            if (index == -1)
                return -1;
            else
            {
                index += error.Length;
                int end = rtn.IndexOf(',', index);
                if (end == -1)
                    return -1;

                error = rtn.Substring(index, end - index);
                if (CheckNumber(error))
                    return int.Parse(error);
                else
                    return -1;
            }
        }

        private int SafeSendTxt(string txt)
        {
            if (m_token.Length < 4)
                m_token = GetWeiXinToken();

            if (m_token.Length < 4)
                return -1;

            int rtn = SendTxt(txt);
            if (rtn == 40001)
            {
                m_token = GetWeiXinToken();
                rtn = SendTxt(txt);
            }
            return rtn;
        }

        private string GetWeiXinToken()
        {
            string m_sCorpKey = GetAK("WeiXinCorpKey"); // "ub3P7T1619Nqy-mLz-I_m09-IoCZ34gU7jbjvJRi3hS9YAu89EICQ0qY6kbcnyHc"; //程序Debug组的秘钥,有权发送消息
            string m_sCorpID = GetAK("WeiXinCorpID");

            if (m_sCorpKey == null | m_sCorpID == null)
                return "";

            string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", m_sCorpID, m_sCorpKey);

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Method = "GET";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = 0;

            //发送请求
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            //得到返回结果
            StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string rtn = php.ReadToEnd();

            //using System.Web.Script.Serialization;
            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            //Project p1 = serializer.Deserialize<Project>(Message);

            string name = "\"access_token\":";

            int index = rtn.IndexOf(name);
            if (index == -1)
                return "";
            else
            {
                index += name.Length;
                int start = rtn.IndexOf('"', index);
                if (start == -1)
                    return "";
                int end = rtn.IndexOf('"', start + 1);
                if (end == -1)
                    return "";

                return rtn.Substring(start + 1, end - start - 1);
            }
        }
        /*-----------OAuth2.0验证接口获得成员身份-------------*/
        /// <summary>
        /// 获取标签成员
        /// </summary>
        /// <param name="code">微信服务器传递来的code</param>
        /// <returns>code对应成员的微信id</returns>
        public string GetUserByCode(string code)
        {
            string rtn = null;
            try
            {

                if (m_token.Length < 4)
                {
                    m_token = GetWeiXinToken();

                }
                string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}", m_token, code);

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

                webRequest.Method = "GET";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = 0;

                //发送请求
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

                //得到返回结果    
                JavaScriptSerializer UserJson = new JavaScriptSerializer();
                StreamReader res = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                OAuth user = UserJson.Deserialize<OAuth>(res.ReadToEnd());
                if (user.errcode != 40029)//不合法的标签ID
                    rtn = user.UserId;
            }
            catch
            {
            }
            return rtn;
        }

        //获取所需要的权限
        public string GetAK(string ak)
        {
            return (System.Configuration.ConfigurationManager.AppSettings[ak].ToString());
        }
    }
}